package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.INetworkTrainRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.train.service.INetworkTrainPointsService;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * network_point控制器
 *
 * @author fengshuonan
 * @Date 2017-12-28 22:33:37
 */
@Controller
@RequestMapping("/networkTrainPoints")
public class NetworkTrainPointsController extends BaseController {

    private String PREFIX = "/train/networkTrainPoints/";

    @Autowired
    private INetworkTrainPointsService networkTrainPointsService;

    @Autowired
    private INetworkTrainRuleService networkTrainRuleService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDictService dictService;

    private static List<NetworkTrainPoints> REPEAT = new ArrayList<>();
    /**
     * 跳转到network_point首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "networkTrainPoints.html";
    }

    /**
     * 跳转到添加network_point
     */
    @RequestMapping("/networkTrainPoints_add")
    public String networkTrainPointsAdd(Model model) {
        List<NetworkTrainRule> networkTrainRules = networkTrainRuleService.selectAll();
        Double upperLimit = networkTrainRuleService.getUpperLimit(networkTrainRules);

        //用工类型
        List<Dict> laborTypes = dictService.getChildByCode(Const.LABOR_TYPE);
        List<Dict> personStates = dictService.getChildByCode(Const.PERSON_STATES);

        model.addAttribute("laborTypes",laborTypes);
        model.addAttribute("personStates",personStates);
        model.addAttribute("rules",networkTrainRules);
        model.addAttribute("upperLimit",upperLimit);
        return PREFIX + "networkTrainPoints_add.html";
    }

    /**
     * 跳转到修改network_point
     */
    @RequestMapping("/networkTrainPoints_update/{networkTrainPointsId}")
    public String networkTrainPointsUpdate(@PathVariable String networkTrainPointsId, Model model) {
        NetworkTrainPoints networkTrainPoints = networkTrainPointsService.selectById(networkTrainPointsId);
        List<NetworkTrainRule> networkTrainRules = networkTrainRuleService.selectAll();
        Double upperLimit = networkTrainRuleService.getUpperLimit(networkTrainRules);

        //用工类型
        List<Dict> laborTypes = dictService.getChildByCode(Const.LABOR_TYPE);
        List<Dict> personStates = dictService.getChildByCode(Const.PERSON_STATES);

        model.addAttribute("laborTypes",laborTypes);
        model.addAttribute("personStates",personStates);
        model.addAttribute("rules",networkTrainRules);
        model.addAttribute("upperLimit",upperLimit);

        model.addAttribute("item",networkTrainPoints);
        LogObjectHolder.me().set(networkTrainPoints);
        return PREFIX + "networkTrainPoints_edit.html";
    }

//    /**
//     * 获取network_point列表
//     */
//    @RequestMapping(value = "/list")
//    @ResponseBody
//    public Object list(String condition) {
//        List<NetworkTrainPoints> networkTrainPointss = networkTrainPointsService.selectList(null);
//        return networkTrainPointss;
//    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            return networkTrainPointsService.selectList(null);
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<NetworkTrainPoints> networkTrainPointss = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<NetworkTrainPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);
            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("annual_credits",min,max);
            }
            networkTrainPointss = networkTrainPointsService.selectList(nwWrapper);
        }


        return networkTrainPointss;
    }

    /**
     * 新增network_point
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(NetworkTrainPoints networkTrainPoints) {
        networkTrainPoints.setCreateDate(new Date());
        networkTrainPoints.setIntegralOrigin(Const.IMPORT_TYPE_SYS);
        networkTrainPointsService.insert(networkTrainPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody NetworkTrainPoints[] repeatData) {

        for (NetworkTrainPoints repeatDatum : repeatData) {

            repeatDatum.setCreateDate(new Date());
            repeatDatum.setIntegralOrigin(Const.IMPORT_TYPE_SYS);

            Double integral = networkTrainRuleService.integralCal(repeatDatum.getAnnualPeriod());
            repeatDatum.setAnnualCredits(integral);
            networkTrainPointsService.insert(repeatDatum);
        }

        return super.SUCCESS_TIP;
    }

    /**
     * 删除network_point
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String networkTrainPointsId) {
        if(networkTrainPointsId.contains(",")){
            List<String> ids = Arrays.asList(networkTrainPointsId.split(","));
            networkTrainPointsService.deleteBatchIds(ids);
        }else{
            networkTrainPointsService.deleteById(networkTrainPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改network_point
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(NetworkTrainPoints networkTrainPoints) {
        networkTrainPointsService.updateById(networkTrainPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * network_point详情
     */
    @RequestMapping(value = "/detail/{networkTrainPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("networkTrainPointsId") String networkTrainPointsId) {
        return networkTrainPointsService.selectById(networkTrainPointsId);
    }


    /**
     * 跳转到导入networkTrainPointsId
     */
    @RequestMapping("/networkTrainPoints_import")
    public String networkTrainPointsImport() {
        return PREFIX + "networkTrainPoints_import.html";
    }

    /**
     * 导入employee
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);
        int count = 2;

        try {
//            Set<String> empCode = employeeService.getEmpCode();
            List<NetworkTrainPoints> networkTrainPointsList = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), NetworkTrainPoints.class, params);
            Date now = new Date();

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<NetworkTrainPoints> noRepeat = new ArrayList<>();
            List<NetworkTrainPoints> hasNameList = new ArrayList<>();

            for (NetworkTrainPoints networkTrainPoint : networkTrainPointsList) {

                networkTrainPoint.setIntegralOrigin(Const.IMPORT_TYPE_XML);
                networkTrainPoint.setCreateDate(now);

                if(StringUtils.isEmpty(networkTrainPoint.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(networkTrainPoint.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(networkTrainPoint.getEmpName()).contains(",")) {
                            //有重名情况
                            networkTrainPoint.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(networkTrainPoint);
                        } else {
                            //无重名、正常插入
                            networkTrainPoint.setEmpCode(nameAndCode.get(networkTrainPoint.getEmpName()));
                            Double integral = networkTrainRuleService.integralCal(networkTrainPoint.getAnnualPeriod());
                            networkTrainPoint.setAnnualCredits(integral);
                            noRepeat.add(networkTrainPoint);
                        }
                    } else {
                        throw new Exception("姓名为 " + networkTrainPoint.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    Double integral = networkTrainRuleService.integralCal(networkTrainPoint.getAnnualPeriod());
                    networkTrainPoint.setAnnualCredits(integral);
                    hasNameList.add(networkTrainPoint);
                }

                count++;

            }

            //不重复，先插入
            if(noRepeat.size() > 0){
                networkTrainPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                networkTrainPointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }

        } catch (Exception e) {
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 计算积分
     * @param hours
     * @return
     */
    @RequestMapping(value = "/integralCal")
    @ResponseBody
    public MvcResult integralCal(Double hours){
        MvcResult mvcResult = new MvcResult();
        mvcResult.setState("200");
        mvcResult.setData(networkTrainRuleService.integralCal(hours));
        return mvcResult;
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<NetworkTrainPoints> networkTrainPoints= networkTrainPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("网络培训积分统计表", "网络培训积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, NetworkTrainPoints.class, networkTrainPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="网络培训积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
